package longrise.phone.com.bjjt_jyb.updata;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.Global;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.android.util.Util;
import com.longrise.android.widget.LButtonBg;
import com.longrise.android.widget.LLinearLayoutView;
import com.tencent.tinker.lib.tinker.TinkerInstaller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.Constant.URLConstant;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.EnCryptDeCrypt;
import longrise.phone.com.bjjt_jyb.Utils.LogUtils;
import longrise.phone.com.bjjt_jyb.Utils.PrefUtils;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;

public class UpdataAPK implements Callback, OnKeyListener {
    private Context context = null;
    private Handler handler = null;
    // APP名称
    private String appName = null;
    //热更新app名称
    private String appName2 = "HNJT_JJAPP_Android_hot";
    // 基础升级地址名称
    private String baseurl = null;
    // 升级版本参数名称
    private String methodname = null;
    // 回调接口
    private CheckVersionListener checkVersionListener;
    // 标识符,为0是为手动检测版本
    private int mark = -1;
    private String _apkurl = null;
    private String _apkurl_hot = null;//热更新下载地址
    private File _apkfile = null;
    private File _apkfile_hot = null;//热更新apk文件
    private DownLoadManager _dm = null;
    private DownLoadManager2 _dm2 = null;//热更新下载类
    private DownloadDialog bar;
    private Dialog _dialog2;
    private String updatamethodname = null;

    SharedPreferences _sp = null;
    private Dialog processDialog;

    public UpdataAPK(Context context, String appName) {
        if (null == context || null == appName || "".equals(appName)) {
            return;
        }
        this.context = context;
        this.appName = appName;
        handler = new Handler(this);
        if (null == this._sp && null != this.context) {
            this._sp = this.context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);
        }
    }

    // add by huxin 新增构造传值获取基础url，和升级方法名
    public UpdataAPK(Context context, String appName, String baseurl, String methodname, String updatamethodname) {
        if (null == context || null == appName || "".equals(appName)) {
            return;
        }
        this.context = context;
        this.appName = appName;
        this.baseurl = baseurl;
        this.methodname = methodname;
        this.updatamethodname = updatamethodname;

        handler = new Handler(this);
        if (null == this._sp && null != this.context) {
            this._sp = this.context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);
        }

    }

    public void setMark(int mark) {
        this.mark = mark;
    }

    public void setCheckVersionListener(CheckVersionListener checkVersionListener) {
        this.checkVersionListener = checkVersionListener;
    }

    @Override
    public boolean handleMessage(Message message) {
        if (null == message) {
            return false;
        }
        switch (message.what) {
            case 100:
                if (null != checkVersionListener) {
                    checkVersionListener.onCheckVersion(-1);
                }
                Bundle bundle = message.getData();
                if (null == bundle) {
                    return false;
                }

                // if(null != context)
                // {
                // if(mark != 0)
                // {
                // SharedPreferences sharedPreferences =
                // context.getSharedPreferences(Global.getInstance().getSPName(),Context.MODE_PRIVATE);
                // long lastUpdateTime = sharedPreferences.getLong("lastUpdateTime",
                // 0);
                // //判断是否需要进行检测
                // if ((lastUpdateTime + (24 * 60 * 60 * 1000)) <
                // System.currentTimeMillis())
                // {
                // lastUpdateTime = System.currentTimeMillis();
                // SharedPreferences.Editor editor =
                // context.getSharedPreferences(Global.getInstance().getSPName(),Context.MODE_PRIVATE).edit();
                // editor.putLong("lastUpdateTime", lastUpdateTime);
                // editor.commit();
                // }
                // else
                // {
                // return false;
                // }
                // }
                // }

                // "1"标识强制升级
                String upgrade = bundle.getString("upgrade");
                String apkurl = bundle.getString("apkurl");
                String remarks = bundle.getString("remarks");
                showDialog(upgrade, apkurl, remarks);

                break;
            case 101:
                if (null != checkVersionListener) {
                    checkVersionListener.onCheckVersion(-1);
                }
                break;
            case 102:
                if (null != checkVersionListener) {
                    checkVersionListener.onCheckVersion(0);
                }
                //调取检查热更新的接口
                getAppUpdateVersion("HNJT_JJAPP_Android_hot", String.valueOf(Global.getInstance().getVersionCode()), "1", "2");
                //getAppUpdateVersion("HNJT_JJAPP_Android_hot", "33", "1", "2");
                break;
            case 103:
                installApk();
                break;
            case 104:
                checkVersion();
            case 105:
                if(null!=_apkfile_hot){
                    String absolutePath = _apkfile_hot.getAbsolutePath();
//                    TinkerInstaller.onReceiveUpgradePatch(context.getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
                    TinkerInstaller.onReceiveUpgradePatch(context.getApplicationContext(), absolutePath);
                }
                break;
        }
        return false;
    }

    /**
     * 检查版本热更新并安装
     * @param appname
     * @param apptrueversion
     * @param clienttype
     * @param versiontype
     */
    private void getAppUpdateVersion(String appname, String apptrueversion, String clienttype, String versiontype) {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        bean.set("appname", appname);
        bean.set("apptrueversion", apptrueversion);
        bean.set("clienttype",clienttype);
        bean.set("versiontype",versiontype);
        LoadDataManagerCar.getInstance(context).callService(null,
                ((BaseApplication) context.getApplicationContext()).getServerUrl(), URLConstant.GETAPPUPDATEVERSION,
                bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            processDialog.cancel();
                        }
                        if (null != result) {
                            EntityBean bean = (EntityBean) result;
                            EntityBean data = bean.getBean("data");
                            String restate = bean.getString("restate");
                            String redes = bean.getString("redes");
                            if ("1".equals(restate)) {
                                try {
                                    EnCryptDeCrypt encryptdecrypt = EnCryptDeCrypt.getInstance();
                                    //sp获取本地版本号，对比是否需要下载安装包，安装热更新文件，重置sp的值

                                    String encryAppVersion = encryptdecrypt.deCrypt(data.getString("appversion"));

                                    String url = data.getString("url");

                                    _apkurl_hot = encryptdecrypt.deCrypt(url);//获取下载apk的url
                                    Integer appversion =Integer.parseInt(encryAppVersion) ;//后台获取的热更新版本号
                                    //对比版本号，存进sp
                                    int appSpVersion = PrefUtils.getInt(context, "appSpVersion", 1);//本地sp版本号
                                    if(appversion>appSpVersion){
                                        //下载热更新包安装
                                        Thread thread = new Thread(null, _doDownLoadApk2, "downloadapkBackground2");
                                        thread.start();
                                        PrefUtils.setInt(context,"appSpVersion",appversion);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else {
                                //Toast.makeText(context, redes, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            processDialog.cancel();
                        }
                        Toast.makeText(context, "数据加载失败，请检查网络是否连接", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            processDialog.cancel();
                        }
                    }
                });

    }

    /**
     * 该业务已上传，提示是否继续上传
     */
    private void showDialog(final String upgrade, final String apkUrl, String remarks) {
        if (null == context || null == upgrade || "".equals(upgrade) || null == apkUrl || "".equals(apkUrl)) {
            return;
        }

        // 自定义对话框
        final Dialog exitDialog = new Dialog(context, R.style.dialog_style);
        exitDialog.setCanceledOnTouchOutside(false);
        exitDialog.setCancelable(false);

        // ==================对话框布局==================
        int roundRadius = Util.dip2px(context, 10);
        LLinearLayoutView dialogBody = new LLinearLayoutView(context);
        dialogBody.setOrientation(LinearLayout.VERTICAL);
        dialogBody.setBackgroundColor(Color.parseColor("#287AC4"), Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"), Color.parseColor("#287AC4"), Color.parseColor("#287AC4"), roundRadius, 0,
                Color.parseColor("#287AC4"));

        // 标题
        int pad = Util.dip2px(context, 10);
        TextView setTitle = new TextView(context);
        setTitle.setGravity(Gravity.CENTER);
        setTitle.setText("版本更新");
        setTitle.setTextSize(17);
        setTitle.setTextColor(Color.WHITE);
        setTitle.setPadding(0, pad, 0, pad);
        dialogBody.addView(setTitle, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        // ------------主体-------------
        LLinearLayoutView bodyLayout = new LLinearLayoutView(context);
        bodyLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        bodyLayout.setOrientation(LinearLayout.VERTICAL);
        bodyLayout.setBackgroundColor2(Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE,
                new float[]{0, 0, 0, 0, roundRadius, roundRadius, roundRadius, roundRadius}, 0,
                Color.parseColor("#55E0E0E0"));
        dialogBody.addView(bodyLayout, (int) (Util.getScreenWidth(context) * 0.7),
                LinearLayout.LayoutParams.WRAP_CONTENT);

        int padNoticeStr = Util.dip2px(context, 20);
        EditText editText = null;

        TextView noticeStr = new TextView(context);
        noticeStr.setPadding(0, padNoticeStr, 0, padNoticeStr);
        noticeStr.setBackgroundColor(Color.WHITE);
        noticeStr.setGravity(Gravity.CENTER);
        noticeStr.setText("有新版本，请及时更新。");
        noticeStr.setTextSize(17);
        noticeStr.setTextColor(Color.parseColor("#AA000000"));
        LinearLayout.LayoutParams noticeStrLP = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        noticeStrLP.weight = 1;
        bodyLayout.addView(noticeStr, noticeStrLP);
        noticeStrLP = null;

        // 分隔线
        View line = new View(context);
        line.setBackgroundColor(Color.parseColor("#E0E0E0"));
        bodyLayout.addView(line, LayoutParams.MATCH_PARENT, 1);

        LinearLayout btnLayout = new LinearLayout(context);
        bodyLayout.addView(btnLayout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        float[] myRoundRadius = null;
        if ("1".equals(upgrade)) {
            // 強制更新，隐藏取消按钮
            myRoundRadius = new float[]{0, 0, 0, 0, roundRadius, roundRadius, roundRadius, roundRadius};
        } else {
            myRoundRadius = new float[]{0, 0, 0, 0, roundRadius, roundRadius, 0, 0};

            // 选择安装，不隐藏取消按钮
            LButtonBg cancelBtn = new LButtonBg(context);
            cancelBtn.setBackgroundColor2(Color.WHITE, Color.parseColor("#E0E0E0"), Color.parseColor("#E0E0E0"), -10,
                    Color.parseColor("#E0E0E0"), new float[]{0, 0, 0, 0, 0, 0, roundRadius, roundRadius}, 0,
                    Color.parseColor("#E0E0E0"));
            cancelBtn.setText("取消");
            cancelBtn.setTextColor(Color.parseColor("#AA000000"));
            cancelBtn.setTextSize(15);
            LinearLayout.LayoutParams cancelLP = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    Util.dip2px(context, 45));
            btnLayout.addView(cancelBtn, cancelLP);
            cancelLP.weight = 1;

            cancelBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    exitDialog.cancel();
                }
            });

            // 分隔线
            View line2 = new View(context);
            line2.setBackgroundColor(Color.parseColor("#E0E0E0"));
            btnLayout.addView(line2, 1, LayoutParams.MATCH_PARENT);
        }
        // 确定按钮
        LButtonBg setOK = new LButtonBg(context);
        setOK.setBackgroundColor2(Color.WHITE, Color.parseColor("#E0E0E0"), Color.parseColor("#E0E0E0"), -10,
                Color.parseColor("#E0E0E0"), myRoundRadius, 0, Color.parseColor("#E0E0E0"));
        setOK.setText("确定");
        setOK.setTextColor(Color.parseColor("#AA000000"));
        setOK.setTextSize(15);
        LinearLayout.LayoutParams setOKLP = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                Util.dip2px(context, 45));
        setOKLP.weight = 1;
        btnLayout.addView(setOK, setOKLP);
        setOK.setTag(editText);
        setOK.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                if(!"1".equals(upgrade)){
                    exitDialog.cancel();
                }
                showdownloadDialog();
                Thread thread = new Thread(null, _doDownLoadApk, "downloadapkBackground");
                thread.start();

            }
        });
        exitDialog.setContentView(dialogBody);
        exitDialog.show();
    }

    private void showdownloadDialog() {
        if (null == context) {
            return;
        }
        View view = View.inflate(context, R.layout.download_dialog_layout, null);
        bar = (DownloadDialog) view.findViewById(R.id.download_dialog);
        _dialog2 = new Dialog(context, R.style.dialog_style);
        _dialog2.setCancelable(false);
        _dialog2.setCanceledOnTouchOutside(false);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        _dialog2.setContentView(view, lp);
        _dialog2.show();
    }

    /**
     * 检查版本更新
     */
    public void checkVersion() {
        String updateUrl = null;
        try {
            if (null == context || null == appName || "".equals(appName)) {
                if (null != handler) {
                    handler.sendEmptyMessage(101);
                }
                return;
            }

            _sp = context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);

            if (null != _sp) {
                updateUrl = _sp.getString("updateUrl",
                        ((BaseApplication) context.getApplicationContext()).getUpdateUrl());
            }
            _sp = null;

            if (null == updateUrl || "".equals(updateUrl)) {
                if (null != handler) {
                    handler.sendEmptyMessage(101);
                }
                return;
            }

            EntityBean bean = new EntityBean();
            bean.set(updatamethodname, appName);
            LoadDataManagerCar.getInstance(context).callService(null, baseurl, methodname, bean,
                    new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            LogUtils.sf("===============>onSuccess");

                            EntityBean _checkVersion_eb = (EntityBean) result;
                            if (_checkVersion_eb == null) {
                                if (null != handler) {
                                    handler.sendEmptyMessage(101);
                                }
                                return;
                            }

                            String appversion = null;

                            appversion = _checkVersion_eb.getString("appversion");
                            if (null == appversion || "".equals(appversion)) {
                                if (null != handler) {
                                    handler.sendEmptyMessage(101);
                                }
                                return;
                            }

                            int iappv = Integer.parseInt(appversion);
                            if (iappv > Global.getInstance().getVersionCode()) {

                                // 版本描述
                                String remarks = _checkVersion_eb.getString("remarks", "");
                                // 是否强制更新标示符
                                //String upgrade = _checkVersion_eb.getString("upgrade", "0");
                                  String upgrade="1";
                                //PrefUtils.setString(context,"remarks",remarks);//强制更新后要存版本的更新描述，首页弹框用
                                // cdn完整路径
                                _apkurl = _checkVersion_eb.getString("cdnpath");
                                if (_apkurl == null || "".equals(_apkurl)) {
                                    String[] apk_path = (String[]) _checkVersion_eb.get("apk", null);

                                    if (null == apk_path || "".equals(apk_path)) {
                                        if (null != handler) {
                                            handler.sendEmptyMessage(101);
                                        }
                                        return;
                                    }
                                    String string = apk_path[0];
                                    if (null != string && !"".equals(string)) {
                                        // APK 完整的下载路径
                                        _apkurl = ((BaseApplication) context.getApplicationContext()).getUpdateUrl() + string;
                                    }
                                }

                                if (null != handler) {
                                    Message message = new Message();
                                    Bundle bundle = new Bundle();
                                    bundle.putString("remarks", remarks);
                                    bundle.putString("upgrade", upgrade);
                                    bundle.putString("apkurl", _apkurl);
                                    message.setData(bundle);
                                    message.what = 100;
                                    bundle = null;
                                    upgrade = null;
                                    handler.sendMessage(message);
                                }
                            } else {
                                if (null != handler) {
                                    handler.sendEmptyMessage(102);
                                }
                            }
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                            LogUtils.sf("===============>onError");
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            LogUtils.sf("===============>onFinished");
                        }
                    });
        } catch (Exception ex) {
            if (null != handler) {
                handler.sendEmptyMessage(101);
            }
        }
    }

    public interface CheckVersionListener {
        public void onCheckVersion(int mark);
    }

    // APK下载类
    class DownLoadManager {
        private boolean isbreak = false;

        public DownLoadManager() {
        }

        public File getFileFromServer(String path, ProgressBar pd) throws Exception {
            if (null == path)
                return null;

            // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return null;
            }
            try {
                HttpURLConnection conn = null;
                URL url = new URL(path);
                if (null != url) {
                    conn = (HttpURLConnection) url.openConnection();
                    if (null != conn) {
                        conn.setConnectTimeout(5000);
                        if (200 == conn.getResponseCode()) {
                            this.isbreak = false;
                            // 获取到文件的大小
                            if (null != pd) {
                                pd.setMax(conn.getContentLength());
                            }
                            InputStream is = conn.getInputStream();
                            String locDir = appName;
                            if (null == locDir) {
                                locDir = "BAOA";
                            }
                            String updateApk = appName + ".apk";
                            File file = new File(Environment.getExternalStorageDirectory(), locDir);
                            if (null != file) {
                                if (!file.exists()) {
                                    file.mkdir();
                                }
                            }
                            file = new File(Environment.getExternalStorageDirectory(), locDir + "/" + updateApk);
                            if (null != file) {
                                if (file.exists()) {
                                    file.delete();
                                }
                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                byte[] buffer = new byte[1024];
                                int len;
                                int total = 0;
                                while ((len = bis.read(buffer)) != -1) {
                                    if (isbreak) {
                                        file = null;
                                        break;
                                    }
                                    fos.write(buffer, 0, len);
                                    total += len;
                                    if (null != pd) {
                                        pd.setProgress(total);
                                    }
                                }
                                fos.close();
                                bis.close();
                                is.close();
                            }

                            return file;
                        }
                    }
                }

            } catch (Exception ex) {
            }
            return null;

        }

        public void stop() {
            this.isbreak = true;
        }
    }

    // 热更新APK下载类
    class DownLoadManager2 {
        private boolean isbreak = false;

        public DownLoadManager2() {
        }

        public File getFileFromServer(String path, ProgressBar pd) throws Exception {
            if (null == path)
                return null;

            // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return null;
            }
            try {
                HttpURLConnection conn = null;
                URL url = new URL(path);
                if (null != url) {
                    conn = (HttpURLConnection) url.openConnection();
                    if (null != conn) {
                        conn.setConnectTimeout(5000);
                        if (200 == conn.getResponseCode()) {
                            this.isbreak = false;
                            InputStream is = conn.getInputStream();
                            String locDir = "hotPatch";
                            String updateApk = new Date().getTime() + ".apk";
                            File file = new File(context.getExternalCacheDir(), locDir);
                            if (null != file) {
                                if (!file.exists()) {
                                    file.mkdir();
                                }
                            }
                            file = new File(context.getExternalCacheDir(), locDir + "/" + updateApk);
                            if (null != file) {

                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                byte[] buffer = new byte[1024];
                                int len;
                                int total = 0;
                                while ((len = bis.read(buffer)) != -1) {
                                    if (isbreak) {
                                        file = null;
                                        break;
                                    }
                                    fos.write(buffer, 0, len);
                                    total += len;
                                    /*if (null != pd) {
                                        pd.setProgress(total);
                                    }*/
                                }
                                fos.close();
                                bis.close();
                                is.close();
                            }

                            return file;
                        }
                    }
                }

            } catch (Exception ex) {
            }
            return null;

        }

        public void stop() {
            this.isbreak = true;
        }
    }

    // 下载数据
    private Runnable _doDownLoadApk = new Runnable() {
        @Override
        public void run() {
            try {
                _apkfile = null;
                if (null != _apkurl && !"".equals(_apkurl)) {
                    if (null == _dm) {
                        _dm = new DownLoadManager();
                    }
                    _apkfile = _dm.getFileFromServer(_apkurl, bar);
                    if (null != handler&&null!=_apkfile) {
                        handler.sendEmptyMessage(103);
                    }else {
                        Toast.makeText(context,"下载失败，请重新启动应用并保证网络通畅",Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception ex) {
            }
        }
    };

    // 下载数据
    private Runnable _doDownLoadApk2 = new Runnable() {
        @Override
        public void run() {
            try {
                _apkfile_hot = null;
                if (null != _apkurl_hot && !"".equals(_apkurl_hot)) {
                    if (null == _dm2) {
                        _dm2 = new DownLoadManager2();
                    }
                    _apkfile_hot = _dm2.getFileFromServer(_apkurl_hot, bar);
                    if (null != handler&&null!=_apkfile_hot) {
                        handler.sendEmptyMessage(105);
                    }
                }
            } catch (Exception ex) {
            }
        }
    };

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (null != this._dialog2 && this._dialog2.isShowing()) {
                _dm.stop();
                this._dialog2.dismiss();
            }
        }
        return false;
    }

    private void installApk() {
        /*
		 * if (null == this._apkfile) { if (null != handler) {
		 * handler.sendEmptyMessage(104); } return; }
		 */

        if (null != context) {
            SharedPreferences sp = context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);
            // 使用默认存储位置
            sp.edit().putBoolean("isFirst", false).commit();
        }

        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(this._apkfile), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 执行打开文件
        context.startActivity(intent);

        // 将平台的IP地址清空
        if (null == this._sp) {
            this._sp = this.context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);
        }

        // 保存新的服务地址
        _sp.edit().putString("serverUrl", null).commit();
        // 更新平台的地址
        _sp.edit().putString("updateUrl", null).commit();
        _dialog2.dismiss();
    }
    private void installApk2() {
        /*
		 * if (null == this._apkfile) { if (null != handler) {
		 * handler.sendEmptyMessage(104); } return; }
		 */



        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(this._apkfile_hot), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 执行打开文件
        context.startActivity(intent);

        // 将平台的IP地址清空
        if (null == this._sp) {
            this._sp = this.context.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE);
        }

        // 保存新的服务地址
        _sp.edit().putString("serverUrl", null).commit();
        // 更新平台的地址
        _sp.edit().putString("updateUrl", null).commit();
        _dialog2.dismiss();
    }
}
